/*
 * @Date: 2025-07-17 21:21:32
 * @LastEditTime: 2025-08-11 21:25:29
 */
import TRTC from "trtc-sdk-v5";
import { genTestUserSig } from "../utils";

interface ITRTCParams {
  sdkAppId: number;
  userId: string;
  userSig: string;
  roomId: number;
}

// TRTC 常用配置
export const TRTC_CFG = {
  sdkAppId: 1600097731,
  sdkSecretKey:
    "666316993b22cf341ec147b4f49833850d30349984777365e6071b66f8ea1edf",
  roomId: 999999,
};

const useTRTC = () => {
  // TRTC 对象
  let trtc: any = null;
  // 计时器
  let timer: NodeJS.Timeout;
  // 重试次数
  const retryTimes = 10;

  if (!trtc) {
    // 创建 TRTC 对象
    trtc = TRTC.create();
  }

  // 进入房间
  const enterRoom = async (params: ITRTCParams) => {
    // 进入房间方法
    const enter = (): Promise<any> =>
      // trtc.enterRoom({ ...params });
      trtc.enterRoom({
        ...params,
        autoReceiveAudio: false,
        enableAutoPlayDialog: false,
      });

    // 重试进入房间方法
    const retryEnterRoom = async (times: number) => {
      return new Promise((resolve, reject) => {
        enter()
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log("retryEnterRoom  err:>> ", err);
            if (times === 0) return reject("进入房间失败");
            timer = setTimeout(() => retryEnterRoom(times - 1), 2000);
          });
      });
    };
    return new Promise((resolve, reject) => {
      retryEnterRoom(retryTimes)
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  };

  const init = async (userId: string, videoDom: HTMLDivElement | null) => {
    // 生成签名
    const { userSig } = genTestUserSig({
      SDKAppID: TRTC_CFG.sdkAppId,
      secretKey: TRTC_CFG.sdkSecretKey,
      userID: userId,
    });
    const params = {
      sdkAppId: TRTC_CFG.sdkAppId,
      userId: userId,
      userSig,
      roomId: TRTC_CFG.roomId,
    };
    await enterRoom(params);

    if (videoDom) {
      await trtc.startLocalVideo({
        view: videoDom,
        // 发布视频
        publish: true,
        // 指定使用前置摄像头
        option: { useFrontCamera: true },
      });
    }
  };

  // 退出房间
  const destroy = async () => {
    if (timer) clearTimeout(timer);
    if (trtc) {
      await trtc.exitRoom();
      if (trtc.destroy) trtc.destroy();
    }
    // trtc = null;
  };

  return { trtc, init, destroy, EVENT: TRTC.EVENT, TYPE: TRTC.TYPE };
};

export default useTRTC;
